/*
 * ttrss-reader-fork for Android
 * 
 * Copyright (C) 2010 N. Braden.
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 3 as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 */

/**
 * 
 */
package org.ttrssreader.widget;

import org.ttrssreader.R;
import org.ttrssreader.controllers.DBHelper;
import org.ttrssreader.gui.ArticleActivity;
import org.ttrssreader.gui.FeedActivity;
import org.ttrssreader.gui.FeedHeadlineActivity;
import org.ttrssreader.model.pojos.Category;
import org.ttrssreader.model.pojos.Feed;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Log;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.Toast;

/**
 * @author Jean Calixte
 *
 */
public class TickerWidget extends AppWidgetProvider {
    private static final String TAG = "TickerWidget";
    private static final int COUNT_MAX = 1000;
    public static final String TOAST_ACTION = "org.ttrssreader.widget.TOAST_ACTION";
    public static final String ARTICLE_ID = "org.ttrssreader.widget.ARTICLE_ID";
    public static final String FEED_ID = "org.ttrssreader.widget.FEED_ID";

    
    public static void update(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
        String title, itemSettings = WidgetConfigureActivity.loadIdPref(context, appWidgetId);
        int itemId, unread;
        Intent intent;
        
        if(itemSettings != null) {
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_ticker);
            Log.d(TAG, itemSettings);
            String[] settings = itemSettings.split("/");
            itemId = Integer.parseInt(settings[1]);
            DBHelper helper = DBHelper.getInstance();
            Feed feed;
            Category cat;
            //ImageView icon = (ImageView) layout.findViewById(R.id.imageViewIcon);
            //TODO: Update this function to load the views for the ticker (R.layout.widget_ticker); may need to use a StackView instead of original Google Reader implementation 
            
            //Log.i(TAG, "App Widget ID: " + appWidgetId + ", itemId: " + Integer.toString(itemId) + ", Title: \"" + title + "\", Unread: " + Integer.toString(unread));
            
            /*views.setTextViewText(R.id.textViewUnread, unread > COUNT_MAX ? COUNT_MAX + "+": String.valueOf(unread));
            views.setTextViewText(R.id.textViewTitle, title);
            views.setViewVisibility(R.id.textViewTitle, 1);*/
            //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
            
            //PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, intent, 0);
            //Log.i(TAG, "Binding OnClick Listener for AppWidget " + appWidgetId + ", itemId: " + Integer.toString(itemId) + ", Title: \"" + title + "\"");
            //views.setOnClickPendingIntent(R.id.flUnread, pendingIntent);
            //appWidgetManager.updateAppWidget(appWidgetId, views);           
        }
    }
    
    private void updateAll(Context context) {
        AppWidgetManager awm = AppWidgetManager.getInstance(context);
        onUpdate(context, awm, awm.getAppWidgetIds(new ComponentName(context,TickerWidget.class)));
    }
    
    @Override
    public void onEnabled(Context context) {
        //super.onEnabled(context);
        //Toast.makeText(context, "onEnabled()", Toast.LENGTH_LONG).show();
        //PackageManager pm = context.getPackageManager();
        //pm.setComponentEnabledSetting(new ComponentName("org.ttrssreader", ".widget.UnreadCountUpdateService"), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
        
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        AppWidgetManager mgr = AppWidgetManager.getInstance(context);
        if(intent.getAction().equals(TOAST_ACTION)) {
            // updateAll(context);
            int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
            int articleId = intent.getIntExtra(ARTICLE_ID, 0), feedId = intent.getIntExtra(FEED_ID, 0);
            Log.d(TAG, "Touched view " + articleId);
            
            Intent openArticleIntent = new Intent(context, ArticleActivity.class);
            openArticleIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            openArticleIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
            openArticleIntent.putExtra(ArticleActivity.ARTICLE_ID, articleId);
            openArticleIntent.putExtra(ArticleActivity.ARTICLE_FEED_ID, feedId);
            context.startActivity(openArticleIntent);
        }
        
        super.onReceive(context, intent);
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        super.onDeleted(context, appWidgetIds);
        
        /*for (int i = 0; i < appWidgetIds.length; i++)
            WidgetConfigureActivity.deleteTitlePref(context, appWidgetIds[i]);*/
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {       
        for (int i = 0; i < appWidgetIds.length; i++) {
            //update(context, appWidgetManager, appWidgetIds[i]);
            
            Intent intent = new Intent(context, TickerWidgetService.class);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
            // When intents are compared, the extras are ignored, so we need to embed the extras
            // into the data so that the extras will not be ignored.
            intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
            RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_ticker);
            rv.setRemoteAdapter(R.id.svTicker, intent);

            // The empty view is displayed when the collection has no items. It should be a sibling
            // of the collection view.
            rv.setEmptyView(R.id.svTicker, R.id.tvEmpty);

            // Here we setup the a pending intent template. Individuals items of a collection
            // cannot setup their own pending intents, instead, the collection as a whole can
            // setup a pending intent template, and the individual items can set a fillInIntent
            // to create unique before on an item to item basis.
            Intent openArticleIntent = new Intent(context, TickerWidget.class);
            openArticleIntent.setAction(TickerWidget.TOAST_ACTION);
            openArticleIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
            intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
            PendingIntent openArticlePendingIntent = PendingIntent.getBroadcast(context, 0, openArticleIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            
            /*Intent openArticleIntent = new Intent(context, ArticleActivity.class);
            openArticleIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
            openArticleIntent.putExtra(ArticleActivity.ARTICLE_ID, intent.getIntExtra(ARTICLE_ID, 0));
            openArticleIntent.putExtra(ArticleActivity.ARTICLE_FEED_ID, intent.getIntExtra(FEED_ID, 0));
            PendingIntent openArticlePendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], openArticleIntent, 0);*/
            
            
            rv.setPendingIntentTemplate(R.id.svTicker, openArticlePendingIntent);

            appWidgetManager.updateAppWidget(appWidgetIds[i], rv);

        }
        
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }
    
    @Override
    public void onDisabled(Context context) {
        super.onDisabled(context);
    }
    
}
